<template>
    <div class="questionnaire">
        <div class="search">
            <div class="left">
                <!-- 项目 -->
                <div class="search_list project_name">
                    <span class="search_text">项目名称：</span>
                    <el-select v-model="project_name" filterable clearable placeholder="请选择">
                        <el-option
                            v-for="item in related_project_list"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </div>
                <!-- 类型 -->
                <div class="search_list">
                    <span class="search_text">问卷分类：</span>
                    <el-select v-model="questionnaire_type" clearable placeholder="请选择">
                        <el-option
                            v-for="item in questionnaire_type_list"
                            :key="item.resourceValue"
                            :label="item.resourceItem"
                            :value="item.resourceValue">
                        </el-option>
                    </el-select>
                </div>
            </div>
            <div class="center">
                <!-- 标题名称 -->
                <div class="search_list question_title">
                    <span class="search_text">问卷标题：</span>
                    <el-input v-model="questionnaire_title" placeholder="输入"></el-input>
                </div>
                <!-- 创建时间 -->
                <div class="search_list">
                    <span class="search_text">创建时间：</span>
                    <el-date-picker
                        v-model="create_time"
                        type="date"
                        placeholder="选择日期">
                    </el-date-picker>
                </div>
            </div>
            <div class="right">
                <!-- 状态 -->
                <div class="search_list">
                    <span class="search_text">问卷状态：</span>
                    <el-select v-model="questionnaire_status" clearable placeholder="请选择">
                        <el-option
                            v-for="item in questionnaire_status_list"
                            :key="item.resourceValue"
                            :label="item.resourceItem"
                            :value="item.resourceValue">
                        </el-option>
                    </el-select>
                </div>
            </div>
        </div>
        <!--列表-->
        <div class="list questionnaire_list blockMould">
            <div class="list_head_button">
                <div class="search_button">
                    <el-button size="mini" type="warning" plain @click="get_questionnaire_info" v-if="is_syncing">获取更新</el-button>
                    <el-button size="mini" type="info" v-if="!is_syncing" disabled>同步中</el-button>
                    <div class="last_update_time">
                        末次更新时间：{{last_update_time}}
                    </div>
                </div>
                <div class="search_name">
                    <el-button size="mini" type="primary" @click="search_list">查询</el-button>
                    <el-button size="mini" @click="reset_list">重置</el-button>
                </div>
            </div>
            <el-table
                :header-cell-style="{background:'#F6F7FB',color:'#666666',height: '50px'}"
                :row-class-name="tableRowClassName"
                :data="questionnaireList">
                <el-table-column
                    prop="createDateTime"
                    label="创建时间"
                    min-width="30">
                </el-table-column>
                <el-table-column
                    prop="title"
                    label="标题"
                    min-width="38">
                    <template slot-scope="scope">
                        <el-tooltip
                            trigger="hover"
                            placement="top"
                            v-model="scope.row.is_show_article_tip"
                            :open-delay="500"
                            effect="dark"
                            :disabled="!scope.row.is_show_article_tip"
                            popper-class="export_button_promit show_all_title">
                            <div slot="content">{{scope.row.title}}</div>
                            <div @mouseenter="showArticleTips($event,scope.row)"
                            class='show_all_tip'>{{scope.row.title}}</div>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="product"
                    label="项目名称"
                    min-width="30">
                    <template slot-scope="scope">
                        <el-tooltip
                            trigger="hover"
                            placement="top"
                            v-model="scope.row.is_show_product_tip"
                            :open-delay="500"
                            effect="dark"
                            :disabled="scope.row.is_show_product_tip"
                            popper-class="export_button_promit show_all_title">
                            <div slot="content">{{scope.row.product}}</div>
                            <div @mouseenter="showProductTips($event,scope.row)" 
                            class='show_all_tip'>{{scope.row.product}}</div>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column
                    label="状态"
                    min-width="18">
                    <template slot-scope="scope">
                        <span :style="{background:scope.row.bgcolor,color:scope.row.color}">{{scope.row.status}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="ptype"
                    label="分类"
                    min-width="18">
                </el-table-column>
                <el-table-column
                    prop="updateDateTime"
                    label="更新时间"
                    min-width="30">
                </el-table-column>
                <el-table-column
                    label="操作"
                    min-width="17">
                    <template slot-scope="scope">
                        <el-tooltip popper-class="operation_button_promit" effect="dark" content="编辑" placement="bottom">
                            <el-button type="text" @click="edit_info(scope.row)">
                                <img src="../../assets/common/edit.svg" alt="">
                            </el-button>
                        </el-tooltip>
                        <el-tooltip popper-class="operation_button_promit" effect="dark" content="编辑" placement="bottom">
                            <el-button type="text" @click="show_active_link(scope.row)">
                                <img src="../../assets/common/active_link.svg" alt="">
                            </el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!--分页-->
            <pagination :page="page" @changeCurrentPage="handleCurrentChange" @changePageSize="handlePageSize"/>
        </div>
        <!-- 链接 -->
        <el-dialog
        title="链接"
        :visible.sync="activeLink"
        width="495px"
        class="active_link_dialog"
        :before-close="closeActiveLinkDialog">
            <div>
                <div class="search_list active_title">
                    <span class="search_text">标题：</span>
                    <span class="search_value">{{active_title}}</span>
                </div>
                <div class="search_list link_url">
                    <span class="search_text">链接：</span>
                    <el-input placeholder="请输入内容" v-model="active_link_url" :disabled="true"></el-input>
                    <el-button
                        class="btn"
                        type="primary"
                        v-clipboard:copy="active_link_url"
                        v-clipboard:success="copy_link">复制链接
                    </el-button>
                </div>
                <div class="search_list qrcode">
                    <span class="search_text">二维码：</span>
                    <div class="qr_code" ref="qrCodeUrl" v-if="is_show_qr_code"></div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer copy_success">
                <span v-show="is_show_copy_success_promit">复制成功</span>
            </span>
        </el-dialog>
        <!-- 同步数据 -->
        <el-dialog
        :visible.sync="sync_data"
        width="364px"
        class="sync_data">
            <div>
                <div class="is_sync_data">
                    <span>{{this.last_sync_time}}已完成最新数据的同步。是否需要再次同步？</span>
                </div>
                <div class="refresh">
                    <span>点击刷新，获取{{this.last_sync_time}}前同步的数据</span>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="mini" type="primary" class="refresh_btn" @click="refresh_list">刷新</el-button>
                <el-button size="mini" type="primary" class="sync_btn" @click="again_sync">再次同步</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import { api, baseAjax, h5Url } from '@/api/api';
    import pagination from '../public/pagination';
    import {statusCode} from '../../utils/index';
    import {formatHour, formatDate} from '../../utils/validate';
    import Cookies from 'js-cookie';
    import QRCode from 'qrcodejs2';
    export default {
        name: "questionnaireManagement",
        data() {
            return {
                //分页
                page: {
                    currentPage: 1,    //当前页
                    pageSize: 10,    //每页显示条数
                    totalPage: 0,   //总页数
                    total:null   //总条数
                },
                dialogVisibleEdit:false,  //是否显示编辑弹框
                activeLink:false,   //是否显示活动链接弹框
                questionnaire_title:'',   //标题筛选项
                project_name:null,   //相关项目筛选项
                project_list:[],    //项目下拉框值
                related_project_list:[],   //相关项目下拉框值
                questionnaire_status:'',   //状态筛选项
                questionnaire_status_list:[],  //状态下拉框值
                questionnaire_type:'',   //类型筛选项
                questionnaire_type_list:[],   //类型下拉框值
                create_time:'',   //创建时间筛选项
                questionnaireList:[],  //列表数据
                last_update_time:'',   //末次更新时间
                active_title:'',    //活动标题
                active_link_url:'',   //活动链接url
                is_show_copy_success_promit:false,   //是否显示复制成功提示
                // is_sync_questionnaire:false,   //是否同步问卷数据
                edit_questionnaire_id:null,   //编辑问卷id
                user_info:{},
                sync_number:0,   //同步次数
                is_syncing:true,   //是否是同步中
                sync_data:false,   //是否提示同步数据
                last_sync_time:null,   //上次同步时间
                is_show_qr_code:false  //是否显示二维码
            }
        },
        components:{
            pagination
        },
        mounted(){
            this.user_info = JSON.parse(this.EncryUtil.decryptByAES(Cookies.get('user_info')));
            this.getQuestionnaireList();
            this.getProductList(); //获取产品
            this.getRelatedProductList();//获取相关产品
            this.getQuestionnaireStatus(); //问卷状态
            this.getQuestionnaireType(); //问卷类型
            this.getLastUpdateTime(); //末次更新时间
            this.get_sync_status();   //获取同步数据状态
        },
        methods: {
            //修改列表tr颜色
            tableRowClassName({row, rowIndex}) {
                if (rowIndex % 2 === 1) {
                return 'success_row';
                }
                return '';
            },
            //改变当前页码
            handleCurrentChange(currentPage) {
                this.page.currentPage = currentPage;
                this.getQuestionnaireList();
            },
            //改变每页条数
            handlePageSize(pageSize){
                this.page.pageSize = pageSize;
                this.getQuestionnaireList();
            },
            //列表数据
            getQuestionnaireList(){
                let that = this;
                let data = {
                    classify:this.questionnaire_type,
                    createDateTime:this.create_time ? formatHour(this.create_time) : '',
                    currentPage:this.page.currentPage,
                    pageSize:this.page.pageSize,
                    productId:this.project_name,
                    status:this.questionnaire_status.length > 0 ? Number(this.questionnaire_status) : '',
                    title:this.questionnaire_title,
                    totalPage:this.page.totalPage
                };
                baseAjax(api.get_questionnaire_list, data, (res)=>{
                    if(res.code === statusCode.success){
                        let {pageSize, totalPage, value, count} = res.data;
                        that.page.pageSize = pageSize;
                        that.page.totalPage = totalPage;
                        that.page.total = count;
                        that.questionnaireList = value;
                        that.questionnaireList.forEach(item=>{
                            item.active_link = h5Url+'/activity/details/questionnaire/'+item.shortId;
                            item.is_show_article_tip = false;   //是否显示全部标题
                            item.is_show_product_tip = false;   //是否显示全部项目
                            if(item.status == '未发布'){
                                item.bgcolor = 'rgba(145, 147, 152, 0.2)';
                                item.color = '#919398';
                            }else if(item.status == '收集中'){
                                item.bgcolor = 'rgba(26, 179, 148, 0.2)';
                                item.color = '#1AB394';
                            }else if(item.status == '暂停中'){
                                item.bgcolor = 'rgba(254, 159, 0, 0.2)';
                                item.color = '#FE9F00';
                            }else if(item.status == '已结束'){
                                item.bgcolor = 'rgba(145, 147, 152, 0.2)';
                                item.color = '#919398';
                            }
                        });
                    }
                });
            },
            //重置
            reset_list(){
                this.questionnaire_title = '';
                this.project_name = null;
                this.questionnaire_status = '';
                this.questionnaire_type = '';
                this.create_time = '';
            },
            //查询
            search_list(){
                this.handleCurrentChange(1);
            },
            //获取更新问卷
            get_questionnaire_info(){
                let that = this;
                api.sync_questionnaire_list = {
                    url:api.sync_questionnaire_list_url+'?repName='+this.user_info.name+'&reSync='+this.sync_number,
                    method:api.sync_questionnaire_list.method
                }
                baseAjax(api.sync_questionnaire_list, '', (res)=>{
                    if(res.code == 200){
                        that.$alert(res.data).then((res)=>{
                            if(res == 'confirm'){
                                that.$router.go(0);
                                that.getLastUpdateTime();
                                that.getQuestionnaireList();
                            }
                            that.get_sync_status();
                        });
                    }else if(res.code == 20020){
                        that.sync_data = true;
                        let time = Number(res.data);
                        if(res.data > 60){
                            let minute = parseInt(time/60);
                            let second = parseInt((parseFloat(time/60)-parseInt(time/60))*60);
                            that.last_sync_time = minute+'分'+second+'秒';
                        }else{
                            that.last_sync_time = time + '秒';
                        }
                    }
                });
            },
            //获取是否是同步中状态
            get_sync_status(){
                let that = this;
                baseAjax(api.sync_questionnaire_status, '', (res)=>{
                    if(res.code === statusCode.success){
                        if(res.data == true){   //获取更新
                            that.is_syncing = true;
                        }else{
                            that.is_syncing = false;   //同步中
                        }
                    }
                });
            },
            //再次同步
            again_sync(){
                this.sync_data = false;
                this.sync_number = 1;
                this.get_questionnaire_info();
                this.getLastUpdateTime();
                this.getQuestionnaireList();
            },
            //刷新页面
            refresh_list(){
                this.get_sync_status();
                this.getLastUpdateTime();
                this.getQuestionnaireList();
                this.$router.go(0);
            },
            //活动链接
            show_active_link(info){
                this.activeLink = true;
                this.active_title = info.title;
                this.active_link_url = info.active_link+'?linkType=activity';
                this.is_show_qr_code = true;
                this.creatQrCode(info.active_link);   //生成二维码
            },
            //复制链接
            copy_link(){
                this.is_show_copy_success_promit = true;
                setTimeout(()=>{
                    this.is_show_copy_success_promit = false;
                },2000);
            },
            //获取编辑信息
            edit_info(info){
                this.$router.push('/editQuestionnaireManagement')
                Cookies.set('question_info', this.EncryUtil.encryptByAES(JSON.stringify(info)), {expires: 24 * 60 * 60 * 1000});
            },
            //获取所有产品
            getProductList(){
                let that = this;
                baseAjax(api.get_all_product, '', (res)=>{
                    if(res.code === statusCode.success){
                        that.project_list = res.data;
                    }
                });
            },
            //获取相关产品
            getRelatedProductList(){
                let that = this;
                baseAjax(api.get_all_product, '', (res)=>{
                    if(res.code === statusCode.success){
                        that.related_project_list = res.data;
                        that.related_project_list.unshift({
                            id:-1,
                            name:'未分配'
                        });
                    }
                });
            },
            //问卷状态
            getQuestionnaireStatus(){
                let that = this;
                api.get_resource_item = {
                    url:api.get_resource_item_url+'wj_status',
                    method:api.get_resource_item.method
                };
                baseAjax(api.get_resource_item, '', (res)=>{
                    if(res.code === statusCode.success){
                        that.questionnaire_status_list = res.data;
                    }
                });
            },
            //问卷类型
            getQuestionnaireType(){
                let that = this;
                api.get_resource_item = {
                    url:api.get_resource_item_url+'wj_ptype',
                    method:api.get_resource_item.method
                };
                baseAjax(api.get_resource_item, '', (res)=>{
                    if(res.code === statusCode.success){
                        that.questionnaire_type_list = res.data;
                    }
                });
            },
            //获取末次更新时间
            getLastUpdateTime(){
                let that = this;
                api.get_questionnaire_last_update_time = {
                    url:api.get_questionnaire_last_update_time_url+'?syncType=questionnaire',
                    method:api.get_questionnaire_last_update_time.method
                };
                baseAjax(api.get_questionnaire_last_update_time, '', (res)=>{
                    if(res.code === statusCode.success){
                        if(res.data == '未知'){
                            that.last_update_time = res.data;
                        }else{
                            that.last_update_time = formatDate(Number(res.data));
                        }
                    }
                });
            },
            //生成二维码
            creatQrCode(activeLink){
                let that = this;
                this.$nextTick(()=>{
                    var code = new QRCode(that.$refs.qrCodeUrl, {
                        text: activeLink, // 需要转换为二维码的内容
                        width: 100,
                        height: 100,
                        colorDark: '#000000',
                        colorLight: '#ffffff',
                        correctLevel: QRCode.CorrectLevel.H
                    })
                    return code;
                });
            },
            //关闭活动链接弹框
            closeActiveLinkDialog(done){
                this.is_show_qr_code = false;
                done();
            },
            //标题展示全部
            showArticleTips(obj, row){
                /*obj为鼠标移入时的事件对象*/
                let currentWidth = this.showTips(row);
                /*cellWidth为表格容器的宽度*/
                const cellWidth = obj.target.offsetWidth

                /*当文本宽度小于||等于容器宽度3倍时，代表文本显示未超过3行*/
                currentWidth <= (3*cellWidth) ? row.is_show_article_tip = false : row.is_show_article_tip = true

                this.$forceUpdate();
                this.$set(row);
            },
            //项目展示全部
            showProductTips(obj, row){
                /*obj为鼠标移入时的事件对象*/
                let currentWidth = this.showTips(row);
                /*cellWidth为表格容器的宽度*/
                const cellWidth = obj.target.offsetWidth

                /*当文本宽度小于||等于容器宽度3倍时，代表文本显示未超过3行*/
                currentWidth <= (3*cellWidth) ? row.is_show_product_tip = false : row.is_show_product_tip = true
                this.$forceUpdate();
                this.$set(row);
            },
            showTips(row){
                /*width为文本在页面中所占的宽度，创建标签，加入到页面，获取width,最后在移除*/
                let TemporaryTag = document.createElement('span');
                TemporaryTag.innerText = row.articleTitle;
                TemporaryTag.className = 'getTextWidth';
                document.querySelector('body').appendChild(TemporaryTag);
                let currentWidth = document.querySelector('.getTextWidth').offsetWidth;
                document.querySelector('.getTextWidth').remove();

                return currentWidth;
            }
        }
    }
</script>

<style lang="less" scoped>
.questionnaire{
    font-family: PingFangSC-Regular, PingFang SC;
    .search {
        .left,.center{
            margin-right:52px;
            .project_name,.question_title{
                margin-bottom:14px;
            }
            .search_list{
                /deep/.el-date-editor{
                    .el-input__prefix{
                        .el-input__icon{
                            line-height:32px;
                        }
                    }
                    .el-input__suffix{
                        .el-input__suffix-inner{
                            .el-input__icon{
                                line-height:32px;
                            }
                        }
                    }
                }
            }
        }
    }
    .questionnaire_list{
        /deep/.el-table{
            tbody{
                tr{
                    td{
                      padding:12px 0 13px 0;
                      .show_all_tip{
                        display:-webkit-box;
                        text-overflow:ellipsis;
                        overflow:hidden;
                        -webkit-line-clamp: 3;
                        -webkit-box-orient:vertical;
                        cursor: pointer;
                      }
                    }
                    td:first-child{
                        padding-left:23px;
                    }
                    td:nth-child(4){
                        .cell{
                          line-height:21px;
                          span{
                              padding:4px 11px;
                              font-size:12px;
                          }
                        }
                    }
                }
            }
        }
    }

    .active_link_dialog{
        /deep/.el-dialog{
            .el-dialog__body{
                .active_title{
                    .search_text{
                        width:57px;
                    }
                    .search_value{
                        margin-left:2px;
                    }
                }
                .link_url{
                    .el-input{
                        width:288px;
                    }
                }
            } 
        }  
    }

    .sync_data{
        top:39%;
        /deep/.el-dialog{
                .el-dialog__body{
                    padding-bottom:10px !important;
                }
                .is_sync_data{
                    font-size:16px;
                    margin-bottom:20px;
                }
                .refresh{
                    color:#aba9a9;
                }
                .el-dialog__footer{
                    .dialog-footer{
                        .refresh_btn{
                            background-color:#fff;
                            color:#409EFF;
                        }
                    }
                }
        }
    }

    i {
      font-size: 20px;
    }
}
</style>
